package hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import servlet.Add;

public class HbaseUtilA extends Add{

    public Integer rowCount(String tablename){
        Integer rowCount = 0;
        try {
            //  创建HBase配置对象
            Configuration configuration = HBaseConfiguration.create();
            // 指定zookeeper集群地址
            configuration.set("hbase.zookeeper.quorum", "192.168.116.11");
            // 创建连接对象
            Connection connection = ConnectionFactory.createConnection(configuration);
            // 获取Table对象,Table负责与记录相关的操作,如增删改查等
            Table table = connection.getTable(TableName.valueOf("goodsmessage"));
            Scan scan = new Scan();
            //FirstKeyOnlyFilter只会取得每行数据的第一个kv，提升count速度
            scan.setFilter(new FirstKeyOnlyFilter());
            ResultScanner rs = table.getScanner(scan);
            for (Result result : rs) {
                rowCount ++;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            //e.printStackTrace()查看完整错误信息
        }
        return rowCount;
    }
    //    添加
    public  String  AddInfo(String id,String name,String price,String time ,String status) throws IOException {
        //  创建HBase配置对象
        Configuration conf =HBaseConfiguration.create();
        // 指定zookeeper集群地址
        conf.set("hbase.zookeeper.quorum","192.168.116.11");
       //客户端可以通过HTable对象与服务端进行CRUD操作（增删改查）
        HTable table = new HTable(conf,"goodsmessage");

        int count=rowCount("goodsmessage")+1;
        //创建put对象
        Put put1 = new Put(Bytes.toBytes(count+""));
        put1.add(Bytes.toBytes("a"),
                Bytes.toBytes("id"),
                Bytes.toBytes(id));
        put1.add(Bytes.toBytes("b"),
                Bytes.toBytes("name"),
                Bytes.toBytes(name));
        put1.add(Bytes.toBytes("c"),
                Bytes.toBytes("price"),
                Bytes.toBytes(price));
        put1.add(Bytes.toBytes("d"),
                Bytes.toBytes("time"),
                Bytes.toBytes(time));
        put1.add(Bytes.toBytes("e"),
                Bytes.toBytes("status"),
                Bytes.toBytes(status));
        //插入数据
        table.put(put1);

        return  "添加学生信息成功";
    }


}
